/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Digr2iD = {
  Controller: {}
};

Digr2iD.Controller.PostRedirector = {
  /**
   * Redirects to custom URL with parameters using POST method.
   *
   * @param url URL to redirect to.
   * Mandatory parameter. Absence of URL silently exits the function.
   * @param parameters parameters to be sent via POST in the form of JSON object where
   * object property name corresponds to parameter name and
   * object property value corresponds to parameter value.
   * Optional function parameter.
   * @param target request target.
   * Optional parameter. If not specified then '_self' is used.
   */
  go: function(url, parameters, target) {
  /* Absence of URL silently exits the function. */
  if (!url) {
    return;
  }

  /* Creating form element which will be used for submission. */
  var form = document.createElement("form");
  form.id = "org_flushpongle_digr2id_js_controller_postredirector_form";
  form.name = form.id;
  form.action = url;
  form.method = "post";

  /* If no target is specified, then page should be opened in the same window and frame. */
  if (!target) {
    target = "_self";
  }
  form.target = target;

  /* Form control must be appended to document body, otherwise submit will not be invoked. */
  document.body.appendChild(form);

  /* Creating set of hidden input fields which will work as parameters. */
  for (var parameterName in parameters) {
    var input = document.createElement("input");
    input.name = parameterName;
    input.value = parameters[parameterName];
    input.type = "hidden";
    form.appendChild(input);
  }

  /* Submitting form. */
  form.submit();

  /* Form control must be removed from document body, it is no longer used. */
  document.body.removeChild(form);
  }
};

Digr2iD.Controller.RPC = {
  Exception: function(type, message) {
    this.type = type;
    this.message = message;
  },

  Handlers: {
    onSuccess: function(context, result) {
      if (context) {
        if (typeof(context) == 'function') {
          context(result);
        }
        else if (typeof(context) == 'object' && context.onSuccess && typeof(context.onSuccess) == 'function') {
          context.onSuccess(result);
        }
      }
    },

    onFailure: function(context, exception) {
      var domainException = exception;
      var errorProcessor = function(exception) {
        alert(exception.message);
      };

      if (context && typeof(context) == 'object') {
        if (context.onFailure && typeof(context.onFailure) == 'function') {
          errorProcessor = context.onFailure;
        }

        var lastDotPosition = exception.name.lastIndexOf('.');

        if (lastDotPosition != -1) {
          var exceptionShortName = exception.name.substring(lastDotPosition + 1);
          for (var property in context) {
            if (property == exceptionShortName && context[property]) {
              var exceptionPropertyValue = context[property];
              if (typeof(exceptionPropertyValue) == 'string') {
                domainException = new EyeStride.RPC.Exception(exception.name, exception.message);
              }
              else if (typeof(exceptionPropertyValue) == 'function') {
                errorProcessor = exceptionPropertyValue(exception.message);
              }

              break;
            }
          }
        }
      }

      errorProcessor(domainException);
    }
  },

  /**
   * Creates callback for asynchronous calls, which separately process success and failure responses.
   *
   * @param context callback context.
   */
  Callback: function(context, strategy) {
    this.adapter = this[strategy](context);

    return true;
  }

};

String.prototype.repeat = function(times) {
  return new Array(times + 1).join(this);
};

String.prototype.cutWithEllipsis = function(desiredLength) {
  if (desiredLength < 3) {
    desiredLength = 3;
  }

  if (this.length > desiredLength) {
    return this.substring(0, desiredLength - 3) + '...';
  }
  else {
    return this;
  }
};
